/* eslint-disable no-shadow */
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHearder from '@/components/PageHeader';

import { FormComponentProps } from '@ant-design/compatible/es/form';
import {
    Card,
    Row,
    Col,
    Button,
    Input,
    Select,
    Table,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

import BindCabinet from './components/bindCabinet';
import { status } from './constant';

const { Item } = Form;
const { Option } = Select;
const { pathname } = window.location;

interface tencentOverviewProps extends FormComponentProps {
    dispatch: Dispatch<any>;
    courierRecharge: any;
    loading: boolean;
    cabinetLoading: any;
    dataList: any;
    bindCabinetList: any;
}

interface tencentOverviewState {
    pageIndex: any;
    pageSize: any;
    searchValues: any;
    visible: boolean;
    serviceId: number;
    type: number; //  1柜子；2老货架；3新货架
}

@connect(({
    tencentOverview: { dataInfo, bindCabinetList },
    loading,
}: any) => ({
    dataInfo,
    bindCabinetList,
    loading: loading.effects['tencentOverview/fetch'],
    cabinetLoading: loading.effects['tencentOverview/fetchBindCabinet'],
}))

class TencentOverviewElem extends Component<tencentOverviewProps, tencentOverviewState> {
    columns = [{
        title: '授权用户',
        dataIndex: 'jlbUserName',
        render: (text: any) => text || '--',
    }, {
        title: '授权区域',
        dataIndex: 'authArea',
        width: 300,
        render: (text: any) => text || '--',
    }, {
        title: '微信公众号',
        dataIndex: 'nickName',
    }, {
        title: '首次授权时间',
        dataIndex: 'createTime',
    }, {
        title: '状态',
        dataIndex: 'status',
        render: (text: any) => {
            let status = '--';
            if (text === 1) {
                status = '已授权';
            } else if (text === 2) {
                status = '解除授权';
            } else if (text === 3) {
                status = '待再次授权';
            }
            return status;
        },

    }, {
        title: '绑定柜体',
        dataIndex: 'bindCabNum',
        render: (text: number, record: any) => (
            <>
                <span
                    style={{ color: '#1890ff', cursor: 'pointer', padding: '10px' }}
                    onClick={() => this.checkCabinet(record.serviceId, text, 1)}
                >{text}
                </span>
            </>
        ),
    }, {
        title: '绑定旧货架',
        dataIndex: 'bindShelfNum',
        render: (text: number, record: any) => (
            <>
                <span
                    style={{ color: '#1890ff', cursor: 'pointer', padding: '10px' }}
                    onClick={() => this.checkCabinet(record.serviceId, text, 2)}
                >{text}
                </span>
            </>
        ),
    }, {
        title: '绑定新货架',
        dataIndex: 'bindNewShelfNum',
        render: (text: number, record: any) => (
            <>
                <span
                    style={{ color: '#1890ff', cursor: 'pointer', padding: '10px' }}
                    onClick={() => this.checkCabinet(record.serviceId, text, 3)}
                >{text}
                </span>
            </>
        ),
    }, {
        title: '更新时间',
        dataIndex: 'updateTime',
    }]

    state: tencentOverviewState = {
        pageIndex: 1,
        pageSize: 20,
        searchValues: {},
        visible: false,
        serviceId: 0,
        type: 1,    //
    };

    componentDidMount() {
        this.setFieldsValue();
        this.fetchImportList();
    }

    static getDerivedStateFromProps(nextProps: any, preState: any) {
        const { location: { query } } = nextProps;
        const { pageIndex, pageSize, ...searchValues } = query;
        return {
            searchValues,
            pageIndex: Number(pageIndex) || 1,
            pageSize: Number(pageSize) || 20,
        };
    }

    componentDidUpdate(prevProps: any, prevState: any) {
        const { searchValues, pageIndex, pageSize } = this.state;
        if (!_.isEqual(searchValues, prevState.searchValues)
            || pageIndex !== prevState.pageIndex
            || pageSize !== prevState.pageSize) {
            this.setFieldsValue();
            this.fetchImportList();
        }
    }

    componentWillUnmount() {
        const { dispatch } = this.props;
        dispatch({ type: 'tencentOverview/clear' });
    }

    // 获取数据
    fetchImportList = () => {
        const { dispatch } = this.props;
        const { pageSize, pageIndex, searchValues } = this.state;
        dispatch({
            type: 'tencentOverview/fetch',
            payload: {
                pageSize,
                pageIndex,
                ...searchValues,
            },
        });
    }

    // 设置表单值
    setFieldsValue = () => {
        const { searchValues } = this.state;
        const { form: { setFieldsValue } } = this.props;
        setFieldsValue(searchValues);
    }

    // 查询
    handleSearch = (e: any) => {
        e.preventDefault();

        const { form: { validateFields } } = this.props;
        validateFields((err, fieldsValue) => {
            if (err) return;

            const query = { pageIndex: 1, ...fieldsValue };
            const { dispatch } = this.props;
            addTab(dispatch, {
                name: '公众号授权概览',
                url: `${pathname}?${qs.stringify(query)}`,
                isTopMenu: true,
            });
        });
    }

    // 重置
    handleFormReset = () => {
        const { form: { resetFields } } = this.props;
        resetFields();

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '公众号授权概览',
            url: pathname,
            isTopMenu: true,
        });
    }

    // 查看绑定柜体的详情
    checkCabinet = (serviceId: number, num: number, type: number) => {
        if (!num) return;

        this.setState({ serviceId, type });
        this.bindCabinet(true);
    }

    bindCabinet = (values: boolean) => {
        this.setState({ visible: values });
        if (!values) this.setState({ serviceId: 0 });
    }

    // 分页
    onSelectChange = (page: number, psize: number | undefined) => {
        const { searchValues } = this.state;
        const query = {
            ...searchValues,
            pageIndex: page,
            pageSize: psize,
        };

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '公众号授权概览',
            url: `${pathname}?${qs.stringify(query)}`,
            isTopMenu: true,
        });
    };

    render() {
        const {
            loading,
            dataInfo,
            dispatch,
            cabinetLoading,
            bindCabinetList,
            form: { getFieldDecorator },
        }: any = this.props;

        const {
            pageSize, pageIndex, visible, serviceId, type
        } = this.state;

        const pagination = dataInfo
            ? {
                total: dataInfo.count,
                pageSize,
                current: pageIndex,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '50', '100'],
                showTotal: () => `共${dataInfo.count}条数据`,
                onChange: this.onSelectChange,
                onShowSizeChange: this.onSelectChange,
            }
            : {};

        return (
            <>
                <PageHearder />

                <Card bordered={false}>
                    <Form onSubmit={this.handleSearch} className="tableListForm">
                        <Row gutter={12}>
                            <Col md={6} sm={24}>
                                <Item label="微信公众号" colon={false}>
                                    {getFieldDecorator('wechatName')(
                                        <Input
                                            allowClear
                                            autoComplete="off"
                                            placeholder="请输入公众号名称"
                                        />,
                                    )}
                                </Item>
                            </Col>
                            <Col md={6} sm={24}>
                                <Item label="授权用户" colon={false}>
                                    {getFieldDecorator('userName')(
                                        <Input
                                            allowClear
                                            maxLength={11}
                                            autoComplete="off"
                                            placeholder="请输入授权用户名称"
                                        />,
                                    )}
                                </Item>
                            </Col>
                            <Col md={6} sm={24}>
                                <Item label="状态" colon={false}>
                                    {getFieldDecorator('status', {
                                        initialValue: '0',
                                    })(
                                        <Select placeholder="请选择">
                                            {status.map((item: any) => (
                                                <Option
                                                    key={item.id}
                                                    value={String(item.id)}
                                                >
                                                    {item.name}
                                                </Option>
                                            ))}
                                        </Select>,
                                    )}
                                </Item>
                            </Col>
                            <Col md={6} sm={24}>
                                <div className="flexFeView" style={{ margin: '0 0 20px 0' }}>
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                        className="smallButton"
                                    >
                                        查询
                                    </Button>
                                    <Button
                                        type="primary"
                                        className="addButton marginL16 smallButton"
                                        onClick={this.handleFormReset}
                                    >
                                        重置
                                    </Button>
                                </div>
                            </Col>
                        </Row>
                    </Form>

                    <Table
                        rowKey="id"
                        loading={loading}
                        columns={this.columns}
                        dataSource={dataInfo.list}
                        pagination={pagination}
                        scroll={{ x: 1200 }}
                    />
                </Card>

                <BindCabinet
                    visible={visible}
                    dispatch={dispatch}
                    loading={cabinetLoading}
                    type={type}
                    serviceId={serviceId}
                    cabinetList={bindCabinetList}
                    bindCabinet={this.bindCabinet}
                />
            </>
        );
    }
}


export default Form.create<tencentOverviewProps>()(TencentOverviewElem);
